package com.leyou.cart.service;

import com.leyou.auth.entity.UserInfo;
import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.interceptor.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.Sku;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caoLei
 * Date: 2018/11/8
 * Time: 11:35
 * *
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    private static final String KEY_PREFIX = "leyou:cart:uid";


    /**
     * 添加到购物车（保存到redis）
     * @param cart
     * @return
     */
    public void addCart(Cart cart) {

        //获取登录用户
        UserInfo user = LoginInterceptor.get();
        //redis中的key
        String key = KEY_PREFIX + user.getId();
        //获取hash操作对象(本质上是一个map)
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);

        Long skuId = cart.getSkuId();
        //记录页面传递过来的数量
        Integer num = cart.getNum();
        //查询是否存在
        Boolean boo = hashOps.hasKey(skuId.toString());
        if (boo) {
            //存在，获取购物车数据
            String json = hashOps.get(skuId.toString()).toString();
            //反序列化
            cart = JsonUtils.parse(json, Cart.class);
            //修改购物车数量
            cart.setNum(cart.getNum() + num);

        } else {
            //不存在，新增数据
            cart.setUserId(user.getId());
            //其他商品信息，需要查询商品微服务
            Sku sku = this.goodsClient.querySkuById(skuId);
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setPrice(sku.getPrice());
            cart.setTitle(sku.getTitle());
        }
        //将购物车数据写入redis
        hashOps.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
    }

    /**
     * 查询购物车
     * @return
     */
    public List<Cart> queryCartList() {
        //获取用户
        UserInfo user = LoginInterceptor.get();
        //定义redis中的key
        String key = KEY_PREFIX + user.getId();
        //判断是否存在购物车
        if (!this.redisTemplate.hasKey(key)) {
            return null;
        }
        //获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);

        //获取redis中的value（json集合）
        List<Object> carts = hashOps.values();
        //判断购物车记录是否为空
        if (CollectionUtils.isEmpty(carts)) {
            return null;
        }
        //将json集合解析为cart集合
        //新建list集合用来装解析过的cart
        List<Cart> cartList = new ArrayList<>();
        //遍历carts
        for (Object cart : carts) {
             Cart cart1 = JsonUtils.parse(cart.toString(), Cart.class);
            cartList.add(cart1);
        }
        //返回cart集合
        return cartList;
    }

    /**
     * 更新购物车（num）
     * @param cart
     * @return
     */
    public void updateNum(Cart cart) {
        //获取用户
        UserInfo user = LoginInterceptor.get();
        //定义redis中的key
        String key = KEY_PREFIX + user.getId();
        //获取hash操作对象（实际是map）
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        //获取前端传来的num
        Integer num = cart.getNum();
        //获取购物车信息
        String cartData = hashOps.get(cart.getSkuId().toString()).toString();
        //反序列化
        cart = JsonUtils.parse(cartData, Cart.class);
        //更新数量
        cart.setNum(num);
        //写入购物车
        hashOps.put(cart.getSkuId().toString(),JsonUtils.serialize(cart));
    }

    /**
     * 删除购物车
     * @param skuId
     */
    public void deleteCart(Long skuId) {

        UserInfo user = LoginInterceptor.get();
        String key = KEY_PREFIX + user.getId();
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        hashOps.delete(skuId.toString());
    }
}
